package hw.ats.news.activity.news;

import hw.ats.news.R;
import hw.ats.news.activity.DBAwareActivity;
import hw.ats.news.model.Cate;
import hw.ats.news.model.News;
import hw.ats.news.ui.BottomTabHostProvider;
import hw.ats.news.ui.CateNavCallback;
import hw.ats.news.ui.CateNavHolder;
import hw.ats.news.ui.CommonUI;
import hw.ats.news.ui.NewsResourceHolder;
import hw.ats.news.util.App;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ViewFlipper;

import com.humanwares.ui.asyncimage.ImageDisplayer;
import com.humanwares.ui.asyncimage.ImageReceivedCallback;
import com.humanwares.ui.asyncimage.ImageReceiver;
import com.humanwares.ui.tabbar.TabHost;
import com.tattermedia.allthataudio.misc.DebugFlag;

public class PhotoAct extends DBAwareActivity implements ImageReceivedCallback, CateNavCallback {
	private static final String TAG = "PhotoAct";
	private List<Cate> cates = null;
	private List<News> items = new ArrayList<News>();
	private GridView gridView = null;
	private TabHost navbar = null;
//	private ImageButton moreBtn = null;
	
	// 페이징
	private int start = 0;
	private int rows = App.ROW_PER_PAGE_PHOTO;
	private boolean hasNext = true;
	
	// 현재 선택된 카테고리
	private Cate cate = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.act_photo);
        
        initData();
        
        // 탭바 초기화
        navbar = CommonUI.renderTabBar(this, BottomTabHostProvider.TAB3);
        
        // 네비게이션바 제목
        CommonUI.renderAppTitle(this);
        
        // 좌측 네비게이션 버튼 = 검색화면이동
        CommonUI.addLeftNavigationButtonSearchEvent(this);
        
        // 우측 네비게이션 버튼 = All That 화면이동
        CommonUI.addRightNavigationButtonAllThatEvent(this);
        
        // 카테고리바 생성
        CommonUI.makeWithCategorizedSubNavigation(this, cates, 0);
        
//        // 사진 더보기 버튼
//        moreBtn = (ImageButton)findViewById(R.id.photo_next_btn);
//        if (moreBtn != null) {
//        	moreBtn.setVisibility(hasNext ? View.VISIBLE : View.INVISIBLE);
//	        moreBtn.setOnClickListener(new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					loadNextData();
//				}
//			});
//        }
        
        // 사진 출력
        
        gridView = (GridView)findViewById(R.id.photo_list);
        gridView.setAdapter(new PhotoAdapter(this));
        gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				News news = items.get(position);			
				Intent intent = new Intent(PhotoAct.this, ViewAct.class);
				intent.putExtra(App.INTENT_EXTRA_NEWS_UID, news.uid);
				intent.putExtra(App.INTENT_EXTRA_CATE_UID, cate != null ? cate.uid : 0);
				intent.putExtra(App.INTENT_EXTRA_ACT_NAME, PhotoAct.class.getName());
			    startActivity(intent);
			}
        });
        gridView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (DebugFlag.isLogEnabled()) 
					Log.d(TAG, "scroll-state="+scrollState);
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (DebugFlag.isLogEnabled()) 
					Log.d(TAG, "scroll-on="+firstVisibleItem+","+visibleItemCount+","+totalItemCount);
				
				//synchronized (this) {
				if (hasNext && totalItemCount == firstVisibleItem + visibleItemCount) { // && moreBtn != null
		    		//moreBtn.setVisibility(View.VISIBLE);
					hasNext = false; // 동시 처리를 막기 위해
					loadNextData();
				}
//				else if (moreBtn != null) {
//					//moreBtn.setVisibility(View.INVISIBLE);
//				}
				//}
			}
		});
    }
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		if (DebugFlag.isLogEnabled()) Log.d(TAG, "onDestroy()");
		closeDatabase();
	}
    
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event)  {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//	    	Intent intent = new Intent(PhotoAct.this, RecmdAct.class);
//	    	startActivity(intent);
//	    	finish();
//	    	overridePendingTransition(0, 0);
//            return true;
//        }
//
//        return super.onKeyDown(keyCode, event);
//    }
    
    /**
     * 이미지 로더
     */
	public void onImageReceived(ImageDisplayer displayer) {
		this.runOnUiThread(displayer);
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        int visibility = navbar.getVisibility();
        navbar.setVisibility(visibility == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
        return false;
    }
    
	@Override
	public void onSelectCateNav(int position, CateNavHolder holder) {
		if (DebugFlag.isLogEnabled()) 
			Log.d(TAG, "position="+position);
		
		Cate cate = holder.select(position);
		
		if (DebugFlag.isLogEnabled()) 
			Log.d(TAG, "cate="+cate.title);
		
		this.cate = cate;
		this.hasNext = false;

		// 카테고리 선택시 최신글로 연결
		HorizontalScrollView sv = (HorizontalScrollView)findViewById(R.id.navcat_scroll);
		int scrollX = sv.getScrollX();
		Intent intent = new Intent(this, RecentAct.class);
		intent.putExtra(App.INTENT_EXTRA_CATE_UID, cate.uid);
		intent.putExtra(App.INTENT_EXTRA_SCROLL_X, scrollX);
		startActivity(intent);
		
		/* 요청으로 막아둠
		items = News.listPhoto(getReadableDatabase(), cate.uid, 0, rows + 1);
		if (items != null && items.size() == rows + 1) {
			items.remove(rows);
			hasNext = true;
		}
		gridView.setAdapter(new PhotoAdapter(this));
		*/
	}
	
	private void initData() {
		loadData();
		cates = Cate.list(getReadableDatabase());
		
    	cate = null;
		int catId = getIntent().getIntExtra(App.INTENT_EXTRA_CATE_UID, 0);
		if (catId > 0) {
			for (Cate c : cates) {
				if (c.uid == catId) {
					cate = c;
					break;
				}
			}
		}
	}
	
	private void loadData() {
		hasNext = false;
		List<News> newItems = (cate == null) ? 
				News.listPhoto(getReadableDatabase(), start, rows + 1) : 
					News.listPhoto(getReadableDatabase(), cate.uid, start, rows + 1);
		if (newItems != null && newItems.size() > 0) {
			if (newItems.size() == rows + 1) {
				newItems.remove(rows);
				hasNext = true;
			}
			items.addAll(newItems);
		}
	}
	
	/**
	 * 다음 페이지 데이터 조회
	 */
    private void loadNextData() {
    	if (DebugFlag.isLogEnabled())
    		Log.d(TAG, "loadNextData");
    	
    	start += App.ROW_PER_PAGE_PHOTO;
    	new AsyncTask<String, Integer, Boolean>() {
    		private ProgressDialog progressDialog;
    		
    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    	    	progressDialog = ProgressDialog.show(
    	        		PhotoAct.this, "알림", "글을 조회하고 있습니다.", true, false);
    		}
    		
			@Override
			protected Boolean doInBackground(String... params) {
				loadData();
				
				return true;
			}
			
			@Override
			protected void onProgressUpdate(Integer... progress) {
			}

			@Override
			protected void onPostExecute(Boolean result) {
				// 데이터가 존재하지 않으면 더보기 버튼을 숨긴다
//				if (!result) {
//					ImageButton btn = (ImageButton)findViewById(R.id.photo_next_btn);
//					if (btn != null) {
//						btn.setVisibility(View.INVISIBLE);
//					}
//				}
//				if (moreBtn != null)
//					moreBtn.setVisibility(hasNext ? View.VISIBLE : View.INVISIBLE);
				
				// 데이터 업데이트
				((BaseAdapter)gridView.getAdapter()).notifyDataSetChanged();
				progressDialog.dismiss();
			}

			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
			}
		}.execute();
    }
    
	private class PhotoAdapter extends BaseAdapter {
		private final static String TAG = "PhotoAdapter";
	   	private final Activity context;

        public PhotoAdapter(Activity context) {
        	this.context = context;
        }

        public int getCount() {
        	if (items == null)
        		return 0;
        	
            return items.size();
        }

        public Object getItem(int position) {
            return items.get(position);
        }

        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            NewsResourceHolder holder = null;
            if (view == null) {
            	LayoutInflater vi = context.getLayoutInflater();
            	view = vi.inflate(R.layout.row_thumb_type1, null);
                holder = new NewsResourceHolder(view);
                view.setTag(holder);
            } else {
            	holder = (NewsResourceHolder)view.getTag();
            }

            News entry = items.get(position);
    		if (entry == null) {
    			return view;
    		}
    		
            if (holder.imageView != null) {
            	holder.imageView.setTag(position);
            	holder.imageView.setImageResource(App.RES_LOADING_225x165);
                new ImageReceiver(entry.thumb_list, (ImageReceivedCallback)context, 
                		holder.imageView, getThumbPath(), position);
            }
            
            if (DebugFlag.isLogEnabled()) 
            	Log.d(TAG,
            		"pos="+position+
            		" img="+holder.imageView+
            		" cv="+convertView+
            		" par="+parent);
            
            if (holder.titleView != null)
            	holder.titleView.setText(entry.title);
            
    		return view;
        }
	}
}
